package com.rzico.sbl.ui.manager

import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Switch
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityPickupBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.PickCategory
import com.rzico.sbl.model.PickData
import com.rzico.sbl.other.showPickupWindow
import com.rzico.sbl.viewmodel.PickupViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.conditionElse
import com.xinnuo.common.extend.conditionFalse
import com.xinnuo.common.extend.conditionIf
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.gone
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.orEmpty
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.extend.textTrim
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.dp2px
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.addOnScrollChanged
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.slimadapter.SlimAdapter

class PickupActivity : BaseActivity(R.layout.activity_pickup) {

    private val mBinding by lazy { ActivityPickupBinding.bind(getRootView()) }

    private val mCategoryList = arrayListOf<PickCategory>()
    private var mCategoryId = ""
    private var mKeyWord = ""

    override fun getViewModel() = get<PickupViewModel>()

    override fun initData() {
        initTitle(title = "自提站点")

        initLayout()
        initSearch()

        getCategories()
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关站点信息！"
            }

            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration(hasHeader = false, bottom = 60f))
                view.addOnScrollChanged(
                    onShow = { mBinding.pickupBottom.bottomShow() },
                    onHide = { mBinding.pickupBottom.bottomHide(55f) }
                )

                mAdapter = SlimAdapter.creator()
                    .register<PickData>(R.layout.item_pickup_list) { jector, bean, index ->
                        jector.apply {
                            text(R.id.item_pickup_title, bean.name)
                            text(R.id.item_pickup_name, bean.linkman.orEmpty())
                            text(R.id.item_pickup_phone, bean.telephone.orEmpty())
                            text(R.id.item_pickup_addr, bean.address.orEmpty())
                            text(R.id.item_pickup_cate, bean.categoryName.orEmpty())

                            getView<View>(R.id.item_pickup_status)
                                .isVisible = bean.outFlag == "1"
                            getView<View>(R.id.item_pickup_cate_ll)
                                .isGone = bean.categoryName.isNullOrEmpty()

                            with<Switch>(R.id.item_pickup_switch) {
                                it.isChecked = bean.status == "success"

                                it.setOnCheckedChangeListener { _, isChecked ->
                                    getViewModel()
                                        .request(
                                            isLoadingBefore = false,
                                            isLoadingAfter = false,
                                            requestUrl = BaseUrl.mngPickUpd,
                                            params = arrayOf(
                                                "id" to bean.id,
                                                "status" to conditionIf(
                                                    isChecked,
                                                    "success",
                                                    "failure"
                                                )
                                            )
                                        )
                                }
                            }

                            clicked(R.id.item_pickup_code) {
                                startActivityEx<PickupCodeActivity>(
                                    "title" to bean.name,
                                    "shopId" to bean.id
                                )
                            }

                            clicked(R.id.item_pickup_sale) {
                                startActivityEx<PickupReportActivity>(
                                    "stationId" to bean.id,
                                    "stationName" to bean.name
                                )
                            }

                            clicked(R.id.item_pickup_cupboard) {
                                startActivityEx<PickupCupboardActivity>(
                                    "pickId" to bean.id
                                )
                            }

                            clicked(R.id.item_pickup_goods) {
                                startActivityEx<PickupGoodsActivity>(
                                    "pickId" to bean.id
                                )
                            }

                            clicked {
                                startActivityEx<PickupModifyActivity>(
                                    "title" to "修改站点",
                                    "mode" to "edit",
                                    "shopId" to bean.id
                                )
                            }

                            longClicked {
                                deleteStation(bean.id, index)
                                true
                            }
                        }
                    }
                    .attachTo(view)
            }
        }

        tvRight?.oneClick { startActivityEx<PickupReportActivity>() }
        ivRight?.let { iv ->
            iv.isVisible = true
            iv.setPadding(dp2px(11f), 0, dp2px(11f), 0)
            iv.setImageResource(R.drawable.ic_more_right_white)

            iv.oneClick {
                showPickupWindow(
                    anchor = iv,
                    onSelect = { index ->
                        when (index) {
                            0 -> startActivityEx<PickupCategoryActivity>()
                            1 -> startActivityEx<PickupReportActivity>()
                            2 -> startActivityEx<PickupReportOrderActivity>()
                        }
                    }
                )
            }
        }
    }

    private fun initSearch() {
        mBinding
            .pickSearch
            .apply {
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        (it.isEmpty() && mKeyWord.isNotEmpty())
                            .condition {
                                mKeyWord = ""
                                updateList()
                            }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    (actionId == EditorInfo.IME_ACTION_SEARCH)
                        .condition {
                            hideSoftInput() //隐藏软键盘

                            searchEdit.text.isBlank()
                                .conditionElse(
                                    actionTrue = { showToast("请输入关键字") },
                                    actionFalse = {
                                        mKeyWord = searchEdit.textTrim
                                        updateList()
                                    }
                                )
                        }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
            }
    }

    private fun initTabLayout() {
        mBinding
            .pickTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mCategoryId = mCategoryList[it.position].id

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                removeAllTabs()
                mCategoryList.forEachIndexed { index, bean ->
                    addTab(
                        this.newTab().setText(bean.name),
                        index == 0
                    )
                }
            }
    }

    override fun initListener() {
        mBinding
            .btAdd
            .oneClick {
                startActivityEx<PickupModifyActivity>(
                    "title" to "添加站点",
                    "mode" to "add"
                )
            }

        // 刷新站点分类
        observe<String>("pickCategory") { getCategories() }

        // 刷新站点item
        LiveEventBus
            .get("pickList", PickData::class.java)
            .observe(getLifecycleOwner()) { result ->
                when (result.extend) {
                    "add" -> {
                        (mCategoryId.isEmpty()
                                || result.categoryId == mCategoryId)
                            .condition {
                                mList += result
                                mAdapter.notifyItemInserted(mList.lastIndex)
                            }
                    }

                    "update" -> {
                        (mCategoryId.isEmpty()
                                || result.categoryId == mCategoryId)
                            .condition {
                                val index = mList
                                    .indexOfFirst {
                                        it is PickData && it.id == result.id
                                    }

                                mList[index] = result
                                mAdapter.notifyItemChanged(index)
                            }
                    }
                }
            }
    }

    /**
     * 删除自提站点
     */
    private fun deleteStation(itemId: String, index: Int) {
        showHintDialog(
            title = "自提站点",
            hint = "确定要删除该自提站点吗？",
            sure = "删除",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngPickDel,
                        params = arrayOf("id" to itemId),
                        onSuccess = {
                            showToast("自提站点删除成功！")

                            mList.removeAt(index - 1)
                            mAdapter.apply {
                                notifyItemRemoved(index)
                                notifyItemRangeChanged(index, mList.size - index)
                            }

                            mBinding.listLayout
                                .emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                    )
            }
        )
    }

    /**
     * 分类列表
     */
    private fun getCategories() {
        getViewModel()
            .categoryList(
                show = "1",
                onSuccess = {
                    mCategoryList.apply {
                        clear()
                        add(PickCategory(name = "全部"))
                        addItems(it)
                    }

                    initTabLayout()
                }
            )
    }

    /**
     * 自提站点列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .stationList(
                page = index,
                keyWord = mKeyWord,
                categoryId = mCategoryId,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}